<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card">
      <el-row style="margin-bottom: 20px;">
        <el-col>
          <el-button type='primary' @click="addRoleDialog">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" border stripe style="width: 100%">
        <!-- 展开列 -->
        <el-table-column type="expand">
          <template v-slot="scope">
            <el-row :class="['bdbottom',i1 === 0 ? 'bdtop' : '','vcenter']" v-for="(item1,i1) in scope.row.children"
              :key="item1.id">
              <!-- 渲染一级权限 -->
              <el-col :span="5">
                <el-tag closable @close="removeAuthById(scope.row,item1)">{{item1.name}}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染二级和三级权限 -->
              <el-col :span="19">
                <!-- 通过循环嵌套渲染二级权限 -->
                <el-row v-for="(item2,i2) in item1.children" :key="item2.id" :class="[i2 === 0 ? '' : 'bdtop',,'vcenter']">
                  <el-col :span="6">
                    <el-tag type="success" closable @close="removeAuthById(scope.row,item2)">{{item2.name}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 通过循环渲染三级权限 -->
                  <el-col :span="18">
                    <el-tag type="warning" v-for="(item3) in item2.children" :key="item3.id" closable @close="removeAuthById(scope.row,item3)">{{item3.name}}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column type="index" label="#">
        </el-table-column>
        <el-table-column prop="name" label="角色名称" width="280">
        </el-table-column>
        <el-table-column prop="description" label="角色描述" width="280">
        </el-table-column>
        <el-table-column label="操作" width="180">
          <!-- 插槽域使用 -->
          <template v-slot="scope">
            <el-tooltip class="item" effect="dark" content="修改角色" placement="top" :hide-after="1000">
              <el-button type="primary" icon="el-icon-edit" size="small " circle @click="showEditDialog(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="删除角色" placement="top" :hide-after="1000">
              <el-button type="danger" icon="el-icon-delete" size="small " circle @click="removeRole(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="分配权限" placement="top" :hide-after="1000">
              <el-button type="success" icon="el-icon-setting" size="small " circle @click="showAssignDialog(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分配权限对话框 -->
      <el-dialog title="分配权限" :visible.sync="assignAuthdialogVisible" width="50%" @close="setAuthDialogClose">
        <!-- 树形空间 -->
        <el-tree :data="authList" :props="treeProps" show-checkbox node-key="id" default-expand-all
          :default-checked-keys="default_checked_keys" ref="treeRef">
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="assignAuthdialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="allotAuths">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 添加角色表单的对话框 -->
      <el-dialog title="添加角色" :visible.sync="addDialogVisible" id="addUser" @close="addDialogClose">
        <!-- 内容主体区 -->
        <el-form :model="addForm" :rules="addRules" ref="addForm" label-width="100px">
          <el-form-item label="角色昵称" prop="name">
            <el-input v-model="addForm.name"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="addForm.description"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUserConfirm">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改角色的对话框表单 -->
      <el-dialog title="修改角色" :visible.sync="editDialogVisible" id="editUser" @close="editDialogClose">
        <!-- 内容主体区 -->
        <el-form :model="editForm" :rules="addRules" ref="editForm" label-width="70px">
          <el-form-item label="角色名称" prop="name">
            <el-input v-model="editForm.name" placeholder="请输入角色名称"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="description">
            <el-input v-model="editForm.description" placeholder="请输入角色描述"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区 -->
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editRoleConfirm">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data () {
    return {
      // 所有角色数据
      roleList: [],
      // 控制分配权限的对话框是否出现
      assignAuthdialogVisible: false,
      // 所有权限的树形结构
      authList: [],
      // 权限树形的属性
      treeProps: {
        children: 'children',
        label: 'name'
      },
      // 默认勾选的权限，通过后端查
      default_checked_keys: [],
      // 需要分配权限的roleId
      roleId: '',
      addDialogVisible: false,
      addForm: {
        name: '',
        description: ''
      },
      // 验证添加用户和修改用户规则
      addRules: {
        name: [{
          required: true,
          message: '请输入角色昵称',
          trigger: 'blur'
        }]
      },
      // 控制修改对话框显示与否
      editDialogVisible: false,
      editForm: {
        id: '',
        name: '',
        description: ''
      }
    }
  },
  created () {
    this.getRoleList()
  },
  methods: {
    // 获取所有用户数据
    async getRoleList () {
      const {
        data: res
      } = await this.$http.post('auth/roles/list')
      if (res.result !== 'SUCCESS') {
        this.$message.error(res.message)
      }
      this.roleList = res.data.roleList
      console.info(this.roleList)
    },
    // 根据id删除
    async removeAuthById (roleInfo, authInfo) {
      const confirmResult = await this.$confirm('此操作将为角色 ' + roleInfo.name + ' 删除权限 ' + name + ' , 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      if (confirmResult === 'confirm') {
        const {
          data: res
        } = await this.$http.get('auth/roles/removeAuth', {
          params: {
            roleId: roleInfo.id,
            authId: authInfo.id
          }
        })
        if (res.result !== 'SUCCESS') {
          return this.$message.error(res.message)
        }
        // 避免页面刷新，重新渲染，选择对该角色重新赋值，因为双向绑定可以使用形参,使用引用类型
        // this.getRoleList()
        roleInfo.children = res.data.authList
        return this.$message.success('删除成功')
      } else {
        return this.$message.info('取消删除')
      }
    },
    // 显示分配权限的对话框
    async showAssignDialog (roleInfo) {
      this.roleId = roleInfo.id
      console.info(roleInfo)
      // 获取所有权限列表
      const {
        data: res
      } = await this.$http.get('auth/auth/list')
      if (res.result !== 'SUCCESS') {
        return this.$message.error(res.message)
      }
      this.authList = res.data.authList
      console.info(roleInfo.children)
      if (roleInfo.children.length > 0 && roleInfo.children !== null) {
        this.getLeafKeys(roleInfo, this.default_checked_keys)
      }
      this.assignAuthdialogVisible = true
    },
    getLeafKeys (node, arr) {
      // 则是三级节点
      if (node.children.length === 0 || node.children === null) {
        return arr.push(node.id)
      }
      node.children.forEach(item =>
        this.getLeafKeys(item, arr))
    },
    setAuthDialogClose () {
      this.default_checked_keys = []
      this.roleId = ''
    },
    // allotAuths发送分配权限请求
    async allotAuths () {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()
      ]
      console.info(keys)
      const data = {
        roleId: this.roleId,
        authList: keys.join(',')
      }
      const Jsondata = this.$qs.stringify(data)
      const {
        data: res
      } = await this.$http.post('auth/roles/editAuth', Jsondata)
      if (res.result !== 'SUCCESS') {
        return this.$message.error(res.message)
      }
      this.$message.success('修改成功')
      this.assignAuthdialogVisible = false
      this.getRoleList()
    },
    addRoleDialog () {
      this.addDialogVisible = true
    },
    addUserConfirm () {
      this.$refs.addForm.validate(async valid => {
        if (!valid) {
          return null
        }
        const {
          data: res
        } = await this.$http.post('auth/role/add', this.addForm)
        if (res.result !== 'SUCCESS') {
          this.$message.error(res.message)
        }
        this.addDialogVisible = false
        return this.$message.success('添加成功')
      })
    },
    // addDialogClose添加窗口关闭行为
    addDialogClose () {
      this.getRoleList()
      this.$refs.addForm.resetFields()
    },
    // showEditDialog打开修改角色对话框
    showEditDialog (roleInfo) {
      this.editDialogVisible = true
      this.editForm.id = roleInfo.id
      this.editForm.name = roleInfo.name
      this.editForm.description = roleInfo.description
    },
    // 提交角色修改
    editRoleConfirm () {
      this.$refs.editForm.validate(async valid => {
        if (!valid) {
          return null
        }
        const {
          data: res
        } = await this.$http.post('auth/role/edit', this.editForm)
        if (res.result !== 'SUCCESS') {
          this.$message.error(res.message)
        }
        this.editDialogVisible = false
        return this.$message.success('修改成功')
      })
    },
    // 关闭修改角色对话框
    editDialogClose () {
      this.getRoleList()
    },
    // 删除角色
    async removeRole (roleInfo) {
      // 询问是否删除
      const confirmResult = await this.$confirm('此操作将永久删除该角色:' + roleInfo.name + ', 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(error => {
        return error
      })
      if (confirmResult === 'confirm') {
        const {
          data: res
        } = await this.$http.get('auth/role/delete', {
          params: {
            id: roleInfo.id
          }
        })
        if (res.result !== 'SUCCESS') {
          this.$message.error(res.message)
        } else {
          this.$message.success('删除角色成功')
          this.getRoleList()
        }
      } else {
        this.$message.info('取消角色用户')
      }
    }

  }

}
</script>

<style lang="less" scoped>
  .el-tag {
    margin: 7px;
  }

  .bdtop {
    border-top: 1px solid #EEE;
  }

  .bdbottom {
    border-bottom: 1px solid #EEE;
  }

  .vcenter {
    display: flex;
    align-items: center;
  }
</style>
